package com.bango.info;

import java.util.Hashtable;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.webkit.WebView;

import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;

public class InfosFunction implements FREFunction {

	@Override
	public FREObject call(FREContext context, FREObject[] arg1) {
		FREObject obj = null;
		
		try {
			
			TelephonyManager mng = (TelephonyManager) context.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
			NetworkInfo info = ((ConnectivityManager) context.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
			
			String userId =  android.provider.Settings.Secure.getString(context.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID) + " - " + mng.getSimOperator();
			
			String connType = "-1";
			if(info != null)
				connType = String.valueOf(info.getType());

			WebView webView = new WebView(context.getActivity());
			String userAgent = webView.getSettings().getUserAgentString();
			webView.destroy();
			
			Hashtable<String, String> table = new Hashtable<String, String>();
			
			table.put( BangoFieldNames.POST_CONNECTIONTYPE , connType );
			table.put( BangoFieldNames.POST_ISROAMING ,  String.valueOf(mng.isNetworkRoaming()) );
			
			table.put( BangoFieldNames.POST_OPERATOR , mng.getNetworkOperator() );
			table.put( BangoFieldNames.POST_OPERATORNAME , mng.getNetworkOperatorName() );
			table.put( BangoFieldNames.POST_COUNTRYISO , mng.getSimCountryIso() );
			table.put( BangoFieldNames.POST_SIM , mng.getSimOperator() );
			table.put( BangoFieldNames.POST_OPERATORCONNECTIONTYPE , String.valueOf(mng.getNetworkType()) );
			
			table.put( BangoFieldNames.POST_DEVICEBRAND , android.os.Build.BRAND );
			table.put( BangoFieldNames.POST_DEVICEMAKE , android.os.Build.DEVICE );
			table.put( BangoFieldNames.POST_DEVICEMODEL , android.os.Build.MODEL );
			table.put( BangoFieldNames.POST_PRODUCT , android.os.Build.PRODUCT );
			table.put( BangoFieldNames.POST_OPERATINGSYSTEMVERSION , android.os.Build.VERSION.RELEASE );
			table.put( BangoFieldNames.POST_DEVICEVERSION , android.os.Build.ID );
			table.put( BangoFieldNames.POST_USERID , userId );
			table.put( "UserAgent" , userAgent );
			table.put( BangoFieldNames.POST_OPERATINGSYSTEM , "Android" );

			obj = FREObject.newObject(makeJSON(table));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return obj;
	}
	
	private String makeJSON(Hashtable<String,String> tab){
		String res = "{";
		for(String i : tab.keySet()){
			res = res + "\"" + i + "\":\""+ tab.get(i) + "\",";
		}
		res = res.substring(0, res.length()-1);
		return res + "}";
	}

}
